import React from 'react';
import QuoteLayer from './bu/QuoteLayer';
import Canvas from '../../core/Canvas';
import OChart from '../../core/OChart';


export default class extends React.Component {
    constructor(props){
        super(props);
        this.ref = React.createRef();
        this.state = {
            legends: [],
        };
    }

    componentWillReceiveProps (nextProps, nextContext) {
        const { data = [] } = nextProps;
        if (this.props.data !== data) {
            this.quoteLayer.data = data;
            this.quoteLayer.make();
            setTimeout(() => {
                this.canvas.paint();
            }, 0);

        }
    }



    componentDidMount() {
        const { data = [], } = this.props;
        this.canvas = new Canvas({
            ele: this.ref.current,
            canAction: false,
        });
        this.quoteLayer = new QuoteLayer(this.canvas, {
            width: this.canvas.width,
            height: this.canvas.height,
        }, data);
        this.quoteLayer.setQuoteEmitter((legends) => {
            this.setState({
                legends
            });
        });
        this.quoteLayer.make();
        this.canvas.addChild(this.quoteLayer);
        this.canvas.paint();
        this.listen();
    }

    listen = () => {
        const { chart = '', name = '' } = this.props;
        OChart.on(`${chart}:onChartMaked`, this._onChartMaked);
    }

    _onChartMaked = (option) => {
        const { xStep, start, end } = option;
        this.quoteLayer.xStep = xStep;
        this.quoteLayer.dataStart = start;
        this.quoteLayer.dataEnd = end;
        this.quoteLayer.make();
        setTimeout(() => {
            this.canvas.paint();
        }, 0);
    }

    render() {
        const { className = '' } = this.props;
        const { legends = [] }  = this.state;
        return (
            <div style={{borderTop: 'solid 1px #E3E3E3', borderBottom: 'solid 1px #E3E3E3'}}>
                <div style={{display: 'flex', padding: '2px 12px'}}>
                {
                    legends.map((item) => (
                        <div style={{color: item.color, flex: 1,}}>
                            {item.label} &nbsp;&nbsp;{item.value}
                        </div>
                    ))
                }
                </div>
                <div className={className} ref={this.ref} style={{borderTop: 'solid 1px #E3E3E3'}} />
            </div>

        )
    }
}
